<script setup lang="ts">
import type {
  FormInstance,
} from 'element-plus'
import {
  ElForm,
  ElFormItem,
  ElInputNumber,
} from 'element-plus'
import type { TableList } from '../types'
import type { CustomDialogInstance } from '@/types'
import DictionaryPicker from '@/components/DictionaryPicker/DictionaryPicker.vue'

import { alarmThresholdApi } from '@/api'

defineProps<{
  modalTitle: string
}>()

const emits = defineEmits<{
  (e: 'save-success'): void
}>()
const info = defineModel<Partial<TableList>>('data', {
  required: true,
})
const rules = shallowReactive({
  alarmThresholdType: [
    { required: true, message: '必填项' },
  ],
  minimumValue: [
    { required: true, message: '必填项' },
    {
      validator(_rule: any, value: any, callback: any) {
        const { maximumValue } = info.value
        if (maximumValue && value >= Number(maximumValue)) {
          callback(new Error('最小值不能超过最大值'))
        }
        else {
          callback()
        }
      },
    },
  ],
  maximumValue: [
    { required: true, message: '必填项' },
    {
      validator(_rule: any, value: any, callback: any) {
        const { minimumValue } = info.value
        if (minimumValue && value <= Number(minimumValue)) {
          callback(new Error('最大值不能小于最小值'))
        }
        else {
          callback()
        }
      },
    },
  ],
})
const dialogRef = ref<CustomDialogInstance | null>(null)
const formRef = ref<FormInstance | null>(null)

async function clickConfirm(done: () => void) {
  const isValid = await formRef.value
    ?.validate()
    .catch(() => {
      done()
    })
  if (!isValid)
    return

  try {
    const data = toValue(info)
    await alarmThresholdApi.saveOrUpdate({
      id: data.id,
      alarmThresholdType: String(
        data.alarmThresholdType || '',
      ),
      maximumValue: data.maximumValue || '',
      minimumValue: data.minimumValue || '',
    })
    close()
    emits('save-success')
  }
  finally {
    done()
  }
}

function open() {
  dialogRef.value?.open()
}
function close() {
  dialogRef.value?.close()
}

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    :title="modalTitle"
    width="500px"
    @confirm="clickConfirm"
  >
    <ElForm
      ref="formRef"
      :model="info"
      :rules="rules"
      label-width="80px"
    >
      <ElFormItem
        label="告警类型"
        prop="alarmThresholdType"
      >
        <DictionaryPicker
          v-model="info.alarmThresholdType"
          code="GAO_JING_LEI_XING"
        />
      </ElFormItem>
      <ElFormItem label="最大值" prop="maximumValue">
        <ElInputNumber
          v-model="info.maximumValue"
        />
      </ElFormItem>
      <ElFormItem label="最小值" prop="minimumValue">
        <ElInputNumber
          v-model="info.minimumValue"
        />
      </ElFormItem>
    </ElForm>
  </CustomDialog>
</template>
